// 标签页切换
document.querySelectorAll('.tab').forEach(tab => {
    tab.addEventListener('click', () => {
        document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
        document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));

        tab.classList.add('active');
        document.getElementById(tab.dataset.tab).classList.add('active');
    });
});

// 响应标签页切换
document.querySelectorAll('.response-tab').forEach(tab => {
    tab.addEventListener('click', () => {
        document.querySelectorAll('.response-tab').forEach(t => t.classList.remove('active'));
        tab.classList.add('active');

        if (tab.dataset.responseTab === 'body') {
            document.getElementById('response-body').classList.remove('hidden');
            document.getElementById('response-headers').classList.add('hidden');
        } else {
            document.getElementById('response-body').classList.add('hidden');
            document.getElementById('response-headers').classList.remove('hidden');
        }
    });
});

// 请求体类型切换
document.getElementById('body-type').addEventListener('change', (e) => {
    if (e.target.value === 'raw') {
        document.getElementById('raw-body').classList.remove('hidden');
        document.getElementById('form-data-body').classList.add('hidden');
    } else if (e.target.value === 'form-data' || e.target.value === 'x-www-form-urlencoded') {
        document.getElementById('raw-body').classList.add('hidden');
        document.getElementById('form-data-body').classList.remove('hidden');
    } else {
        document.getElementById('raw-body').classList.add('hidden');
        document.getElementById('form-data-body').classList.add('hidden');
    }
});

// 添加行功能
function addTableRow(tableId, columns, withDescription = false) {
    const tbody = document.getElementById(tableId);
    const row = document.createElement('tr');

    columns.forEach(col => {
        const td = document.createElement('td');
        const input = document.createElement('input');
        input.type = 'text';
        input.placeholder = col;
        td.appendChild(input);
        row.appendChild(td);
    });

    if (withDescription) {
        const td = document.createElement('td');
        const input = document.createElement('input');
        input.type = 'text';
        input.placeholder = '描述';
        td.appendChild(input);
        row.appendChild(td);
    }

    const removeTd = document.createElement('td');
    const removeBtn = document.createElement('button');
    removeBtn.textContent = '×';
    removeBtn.classList.add('remove-row');
    removeBtn.addEventListener('click', () => row.remove());
    removeTd.appendChild(removeBtn);
    row.appendChild(removeTd);

    tbody.appendChild(row);
}

document.getElementById('add-param').addEventListener('click', () => {
    addTableRow('params-body', ['参数名', '参数值'], true);
});

document.getElementById('add-header').addEventListener('click', () => {
    addTableRow('headers-body', ['请求头名', '请求头值']);
});

document.getElementById('add-form-data').addEventListener('click', () => {
    addTableRow('form-data-body-content', ['键', '值']);
});

// 发送请求
document.getElementById('send-btn').addEventListener('click', async () => {
    const method = document.getElementById('method').value;
    const url = document.getElementById('url').value;

    // 收集请求头
    const headers = {};
    document.querySelectorAll('#headers-body tr').forEach(row => {
        const inputs = row.querySelectorAll('input');
        if (inputs[0].value && inputs[1].value) {
            headers[inputs[0].value] = inputs[1].value;
        }
    });

    // 准备请求体
    let body = null;
    const bodyType = document.getElementById('body-type').value;

    if (bodyType === 'raw') {

        if (!headers['content-type']) {
            headers['content-type'] = "application/json"
        }

        body = document.getElementById('body-content').value;
    } else if (bodyType === 'form-data' || bodyType === 'x-www-form-urlencoded') {
        const formData = {};
        document.querySelectorAll('#form-data-body-content tr').forEach(row => {
            const inputs = row.querySelectorAll('input');
            if (inputs[0].value) {
                formData[inputs[0].value] = inputs[1].value;
            }
        });

        if (bodyType === 'x-www-form-urlencoded') {

            if (!headers['content-type']) {
                headers['content-type'] = "application/x-www-form-urlencoded"
            }

            body = new URLSearchParams();
            for (const key in formData) {
                body.append(key, formData[key]);
            }
            body = body.toString();
        } else {
            body = JSON.stringify(formData);
        }
    }

    // 更新UI显示正在加载
    document.getElementById('status-code').textContent = '发送中...';
    document.getElementById("container").style.opacity = '0.5'
    document.getElementById("loading").style.display = ''

    document.getElementById('status-code').style.color = 'var(--secondary-color)';

    try {
        const startTime = Date.now();

        const response = await fetch('/api', {
            method: 'POST',
            headers: {
                'content-type':'application/json'
            },
            body: JSON.stringify({
                method,
                url,
                headers,
                body
            })
        });

        console.log(response)

        // 正确遍历 headers 的方法
        const responseHeaders = {};
        response.headers.forEach((value, key) => {
            responseHeaders[key] = value;
        });

        const contentType = responseHeaders['content-type'] || '';

        let responseData;

        if (contentType.includes('application/json')) {
            responseData =  JSON.stringify(await response.json(), null, 2);
        } else if (contentType.includes('text/')) {
            responseData = await response.text();
        } else {
            // 二进制或其他类型数据
            responseData = await response.blob();
        }

        const endTime = Date.now();

        // 更新响应状态
        document.getElementById('status-code').textContent = response.status;
        document.getElementById('status-code').style.color = response.ok ? 'var(--success-color)' : '#dc3545';
        document.getElementById('response-time').textContent = `${endTime - startTime}ms`;

        // 显示响应体
        document.getElementById('response-body').textContent = responseData;


        // 显示响应头
        document.getElementById('response-headers').textContent = JSON.stringify(responseHeaders, null, 2);

    } catch (error) {
        document.getElementById('status-code').textContent = '错误';
        document.getElementById('status-code').style.color = '#dc3545';
        document.getElementById('response-body').textContent = "页面报错" + error.message;
    } finally {
        document.getElementById("container").style.opacity = '1'
        document.getElementById("loading").style.display = 'none'
    }
});

// 复制响应
document.getElementById('copy-response').addEventListener('click', () => {
    const responseText = document.getElementById('response-body').textContent;
    navigator.clipboard.writeText(responseText).then(() => {
        alert('响应已复制到剪贴板');
    });
});